<template>
  <common-layout title="角色管理">
    <template #header-buttons>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增角色
      </el-button>
    </template>

    <template #search-form>
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="角色名称" style="width: 260px;">
          <el-input v-model="searchForm.roleName" placeholder="请输入角色名称" />
      </el-form-item>
      <el-form-item label="角色状态" style="width: 260px;">
        <el-select v-model="searchForm.status" placeholder="请选择状态">
          <el-option label="全部" value="-1" />
          <el-option label="启用" value="true" />
          <el-option label="禁用" value="false" />
        </el-select>
      </el-form-item>
      <el-form-item style="width: auto;">
        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
        <el-button @click="handleReset">
          <el-icon><Refresh /></el-icon>
          重置
        </el-button>
      </el-form-item>
    </el-form>
    </template>

    <template #data-content>
    <!-- 角色列表 -->
    <el-table :data="roles" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="角色ID" width="80" />
        <el-table-column prop="roleName" label="角色名称" width="180" />
        <el-table-column prop="description" label="角色描述" />
        <el-table-column prop="createdTime" label="创建时间" width="180" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-switch 
              v-if="scope.row && scope.row.status !== undefined"
              :model-value="scope.row.status"
              :active-value="true"
              :inactive-value="false"
              @update:model-value="(value) => handleStatusChange(scope.row.id, value)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="260" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="success" size="small" @click="handlePermission(scope.row)">权限设置</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    </template>

    <!-- 新增/编辑角色对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" />        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入角色描述" />        </el-form-item>
        <el-form-item label="角色状态" prop="status">
          <el-switch v-model="form.status" :active-value="true" :inactive-value="false" />        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 权限设置对话框 -->
    <el-dialog v-model="permissionDialogVisible" title="权限设置" width="600px">
      <div v-if="currentRole">
        <h3>{{ currentRole.roleName }} - 权限配置</h3>
        <el-tree
          v-model="checkedPermissions"
          :data="permissions"
          show-checkbox
          node-key="id"
          default-expand-all
        />
      </div>
      <template #footer>
        <el-button @click="permissionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handlePermissionSubmit">确定</el-button>
      </template>
    </el-dialog>
  </common-layout>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import { Search, Refresh, Plus } from '@element-plus/icons-vue';
import type { Role } from '@/types/role';
import apiRequest from '@/utils/apiRequest';
import CommonLayout from '../components/CommonLayout.vue';

// 初始化角色和权限数据
const roles = ref<Role[]>([]);
const permissions = ref([]);
const rolePermissions = ref({});
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const loading = ref(false);

// 搜索表单数据
const searchForm = reactive({
  roleName: '',
  status: '-1'
});

// 获取角色列表
const getRoles = async () => {
  loading.value = true;
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      roleName: searchForm.roleName,
      status: searchForm.status !== '-1' ? searchForm.status : undefined
    };
    const response = await apiRequest.get('/api/Roles', { params });
    roles.value = response.data?.$values || [];
    total.value = roles.value.length;
  } catch (error) {
    ElMessage.error('获取角色列表失败: ' + (error as Error).message);
    console.error('Failed to get roles:', error);
  } finally {
    loading.value = false;
  }
};

// 搜索角色
const handleSearch = () => {
  currentPage.value = 1;
  getRoles();
};

// 重置搜索
const handleReset = () => {
  searchForm.roleName = '';
  searchForm.status = '-1';
  currentPage.value = 1;
  getRoles();
};

// 获取权限列表
const getPermissions = async () => {
  try {
    const response = await apiRequest.get('/api/Permissions');
    permissions.value = response.data?.$values || [];
  } catch (error) {
    ElMessage.error('获取权限列表失败: ' + (error as Error).message);
    console.error('Failed to get permissions:', error);
  }
};

// 获取角色权限
const getRolePermissions = async (roleId: number) => {
  try {
    const response = await apiRequest.get(`/api/Roles/${roleId}/permissions`);
    rolePermissions.value[roleId] = response.data?.$values || [];
    return rolePermissions.value[roleId];
  } catch (error) {
    ElMessage.error('获取角色权限失败: ' + (error as Error).message);
    console.error(`Failed to get permissions for role ${roleId}:`, error);
    return [];
  }
};

const dialogVisible = ref(false);
const dialogTitle = ref('新增角色');
const formRef = ref(null);
const form = reactive<Partial<Role>>({
  id: 0,
  roleName: '',
  description: '',
  status: true
});
const permissionDialogVisible = ref(false);
const currentRole = ref<Role | null>(null);
const checkedPermissions = ref([]);

const rules = {
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '角色名称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '角色描述最多 200 个字符', trigger: 'blur' }
  ]
};

// 新增角色
const handleAdd = () => {
  dialogTitle.value = '新增角色';
  form.id = 0;
  form.roleName = '';
  form.description = '';
  form.status = true;
  dialogVisible.value = true;
};

// 编辑角色
const handleEdit = (row: Role) => {
  dialogTitle.value = '编辑角色';
  form.id = row.id;
  form.roleName = row.roleName;
  form.description = row.description;
  form.status = row.status;
  dialogVisible.value = true;
};

// 提交表单
const handleSubmit = async () => {
  (formRef.value as any).validate(async (valid: boolean) => {
    if (valid) {
      // 调用真实API
      if (form.id === 0) {
        // 新增
        try {
          await apiRequest.post('/api/Roles', form);
          ElMessage({ message: '角色添加成功', type: 'success' });
          // 重新获取角色列表
          await getRoles();
        } catch (error) {
          ElMessage.error('添加角色失败: ' + (error as Error).message);
          console.error('Failed to add role:', error);
        }
      } else {
        // 编辑
        try {
          await apiRequest.put(`/api/Roles/${form.id}`, form);
          ElMessage({ message: '角色更新成功', type: 'success' });
          // 重新获取角色列表
          await getRoles();
        } catch (error) {
          ElMessage.error('更新角色失败: ' + (error as Error).message);
          console.error('Failed to update role:', error);
        }
      }
      dialogVisible.value = false;
    }
  });
};

// 删除角色
const handleDelete = (row: Role) => {
  // 不能删除超级管理员
  if (row.id === 1) {
    ElMessage({ message: '超级管理员不能删除', type: 'error' });
    return;
  }

  ElMessageBox.confirm(
    `确定要删除角色 ${row.roleName} 吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      // 调用真实API
      try {
        await apiRequest.delete(`/api/Roles/${row.id}`);
        ElMessage({ message: '角色删除成功', type: 'success' });
        // 重新获取角色列表
        await getRoles();
        // 删除对应的角色权限
        delete rolePermissions.value[row.id];
      } catch (error) {
        ElMessage.error('删除角色失败: ' + (error as Error).message);
        console.error('Failed to delete role:', error);
      }
    })
    .catch(() => {
      ElMessage({ message: '已取消删除', type: 'info' });
    });
};

// 状态变更
const handleStatusChange = async (roleId, newStatus) => {
  try {
    // 根据roleId查找对应的角色对象
    const role = roles.value.find(r => r.id === roleId);
    if (!role) {
      console.error('未找到角色:', roleId);
      return;
    }

    // 创建包含完整字段的更新对象
    const updatedRoleData = {
      ...role,
      status: newStatus,
      updatedTime: new Date().toISOString(),
      // 将可能为null的导航属性设置为空数组
      userRoles: role.userRoles || [],
      rolePermissions: role.rolePermissions || []
    };

    
    

    // 发送PUT请求更新角色
    const response = await apiRequest.put(`/api/Roles/${roleId}`, updatedRoleData);
    

    // 更新本地角色列表中的状态
    role.status = newStatus;
    ElMessage({ type: 'success', message: '角色状态更新成功' });
  } catch (error) {
    console.error('API请求错误:', error);
    console.error('更新角色状态失败:', error);
    console.error('错误详情:', error.response?.data);
    // 新增: 输出具体的验证错误字段
    console.error('验证错误字段:', error.response?.data?.errors);
    console.error('请求数据:', error.config?.data);
    console.error('请求URL:', error.config?.url);
    ElMessage({ type: 'error', message: '角色状态更新失败' });
  }
};

// 权限设置
const handlePermission = async (row: Role) => {
  currentRole.value = row;
  // 获取角色权限
  const rolePerms = await getRolePermissions(row.id);
  checkedPermissions.value = rolePerms.map((perm: any) => perm.id);
  permissionDialogVisible.value = true;
};

// 提交权限设置
const handlePermissionSubmit = async () => {
  if (!currentRole.value) return;

  try {
    await apiRequest.post(`/api/Roles/${currentRole.value.id}/permissions`, {
      permissionIds: checkedPermissions.value
    });
    ElMessage.success('权限设置成功');
    // 更新本地角色权限
    rolePermissions.value[currentRole.value.id] = checkedPermissions.value.map(id => ({
      id
    }));
    permissionDialogVisible.value = false;
  } catch (error) {
    ElMessage.error('权限设置失败: ' + (error as Error).message);
    console.error('Failed to set permissions:', error);
  }
};

// 分页处理
const handleSizeChange = (size: number) => {
  // 实现分页大小变更逻辑
};

const handleCurrentChange = (current: number) => {
  currentPage.value = current;
  // 实现分页当前页变更逻辑
};

// 初始加载
onMounted(async () => {
  await getRoles();
  await getPermissions();
});
</script>

<style scoped>
/* 原有样式被CommonLayout组件样式替代 */

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>